import {writeFile} from "node:fs";
import {ElMessage, type UploadFile} from "element-plus";
// import {onStartExec} from "@/utils/upload";

/**
 * 导出JSON
 * @param localPath
 * @param data
 * @param filename
 */
export const exportJson = (localPath: string, data: object, filename: string): Promise<any> => {
  return new Promise((resolve, reject) => {
    // 将数据转换为JSON字符串
    const jsonData = JSON.stringify(data, null, 2);
    writeFile(`${localPath}/${filename}`, jsonData, (error) => {
      if (error) {
        reject(error)
        throw error
      }
      // onStartExec(localPath)
      ElMessage.success('导出成功。')
      resolve(localPath)
    })
  })
}

/**
 * 导入JSON
 * @param file
 */
export const importJson = (file: UploadFile): Promise<any> => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onload = (e) => {
      const content = String(e.target?.result)
      try {
        const json = JSON.parse(content)
        resolve(json)
        ElMessage.success('导入成功。')
      } catch (e) {
        reject()
      }
    }
    reader.onerror = function (e) {
      // 文件读取出错后的处理
      reject(e.target?.error)
    }
    // 以文本形式读取文件
    if (file.raw) reader.readAsText(file.raw);
    else reject()
  })
}
